package com.voice.server.auth.handle;

import com.voice.core.entity.HttpHeader;
import com.voice.server.auth.Authorization;
import com.voice.server.entity.Device;
import com.voice.server.enums.DeviceStatusEnum;
import com.voice.server.repository.DeviceRepository;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component("deviceKey")
public class  DeviceAuthorization implements Authorization {

    @Autowired
    private DeviceRepository deviceRepository;

    private static final String PARAM_SIGN = "param-sign";
    private static final String PARAM_SIGN_METHOD = "param-sign-method";

    private static final String PARAM_RANDOM = "param-random";


    @Override
    public String authorization(HttpHeader requestHeader) {
        String deviceKey=requestHeader.get("deviceKey",String.class);
        String random=requestHeader.get(PARAM_RANDOM,String.class);
        String method=requestHeader.get(PARAM_SIGN_METHOD,String.class);
        String validSign=requestHeader.get(PARAM_SIGN,String.class);

        Device device=deviceRepository.findByDeviceKey(deviceKey);
        if(device==null) return null;
        if(device.getStatus()== DeviceStatusEnum.Create.getCode()) return null;
        String deviceSecret =device.getDeviceSecret();
        String signOrigin = "deviceSecret=" + deviceSecret +"random=" + random;
        try {
            String sign = (new HmacUtils(HmacAlgorithms.valueOf(method), deviceSecret)).hmacHex(signOrigin);
            if(!sign.equals(validSign)) return null;
        }catch (IllegalArgumentException e){
            return null;
        }
        String mac=requestHeader.get("mac",String.class);
        if(device.getMac()!=null) return device.getUserId();
        device.setMac(mac);
        deviceRepository.save(device);
        return device.getUserId();
    }

}
